package br.ufpe.cin.msc.jrsj2.recommender.persistence.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import br.ufpe.cin.msc.jrsj2.recommender.persistence.dao.ChannelDAO;
import br.ufpe.cin.msc.jrsj2.recommender.persistence.domain.Channel;

public class JPAChannelDAO implements ChannelDAO {

	private EntityManager emf;

	public JPAChannelDAO(EntityManager emf) {
		this.emf = emf;
	}

	@Override
	public Channel create(Channel channel) {
		String serviceLocation = channel.getServiceLocation();

		if (serviceLocation == null || serviceLocation.isEmpty())
			; // TODO: Throw exception
		if (serviceLocation.charAt(serviceLocation.length() - 1) != '/') {
			serviceLocation += "/";
			channel.setServiceLocation(serviceLocation);
		}

		try {
			emf.getTransaction().begin();
			emf.persist(channel);
			emf.getTransaction().commit();
			return channel;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	@Override
	public Channel findByName(String name) {
		try {
			return (Channel) emf
					.createQuery("SELECT c FROM Channel c WHERE c.name = :name")
					.setParameter("name", name).getSingleResult();
		} catch (NoResultException ex) {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Channel> loadAll() {
		return emf.createQuery("SELECT c FROM Channel c").getResultList();
	}

	@Override
	public void removeByName(String name) {
		if (name == null)
			return;

		Channel channel = findByName(name);

		if (channel == null)
			return;

		try {
			emf.getTransaction().begin();
			emf.remove(channel);
			emf.getTransaction().commit();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
